extends Control



#onready var name_input = $addDrmaModal/VBoxContainer/name/LineEdit
#onready var data_input = $addDrmaModal/VBoxContainer/darmaData/TextEdit
#onready var next_drama_op = $addDrmaModal/VBoxContainer/nextDarma/OptionButton


var dramaItem = preload("res://tool/page/drama/dramaItem.tscn")

# 当前正在编辑的剧本数据，添加剧本数据为空
var edit_drama_data = null

onready var search_input = $searchBox/LineEdit


func _ready():
	state_update()


# 刷新页面状态
func state_update():
	
	update_list(DataSource.get_data_list(DataSource.drama))


func update_list(list):
	var box = $table/ScrollContainer/VBoxContainer
	
	for child in box.get_children():
		child.queue_free()
		
	for drama_data in list:
		var ui_item = dramaItem.instance()
		ui_item.set_data(drama_data)
		box.add_child(ui_item)
		ui_item.connect("edit", self, "_on_edit")
		ui_item.connect("delete", self, "_on_delete")


func _on_addBtn_button_up():
	var ui = MainTool.getUILayer().add_ui("res://tool/page/drama/modal/DramaModal.tscn", 0, false)
	
	ui.connect("close", self, "state_update")


func _on_edit(drama_data):
	var ui = MainTool.getUILayer().add_ui("res://tool/page/drama/modal/DramaModal.tscn", 0, false)
	ui.connect("close", self, "state_update")
	
	ui.set_edit_data(drama_data)


func _on_delete(drama_data):
	MainTool.confirm("你是否确认删除剧本%s"%drama_data["name"], self, "on_del_ok", null, drama_data['id'])
	
func on_del_ok(id):
	DataSource.delete_data_by_id(DataSource.drama, id)
	state_update()


func _on_search_button_up():
	var text = search_input.text
	
	if text:
		var list = []
		for map in DataSource.get_data_list(DataSource.drama):
			if map["name"].find(text) != -1:
				list.append(map)
				
		update_list(list)
	else:
		update_list(DataSource.get_data_list(DataSource.drama))
